package cn.myjerry.test.JDBC;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 测试CLOB 文本大对象的使用
 * @author Jerry
 *
 */
public class Demo08 {
	// JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/testjdbc?useSSL=true&useUnicode=true&characterEncoding=utf8";
    
    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "Jerry1912317";
	
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		// 加载驱动类
		try {
			Class.forName(JDBC_DRIVER);
			conn = DriverManager.getConnection(DB_URL, USER, PASS);
			
//			ps = conn.prepareStatement("UPDATE User SET MyInfo=? WHERE Id=3009");
//			//ps.setClob(1, new FileReader(new File("/Users/zpon/workspace/node/test/onput.txt")));
//			ps.setClob(2, new BufferedReader(new InputStreamReader(new ByteArrayInputStream("bbbbbbbb".getBytes()))));
//			ps.executeUpdate();
			
			ps = conn.prepareStatement("SELECT * FROM User WHERE Id = ?");
			ps.setInt(1, 3009);
			res = ps.executeQuery();
			while(res.next()) {
				Clob c = res.getClob("MyInfo");
				Reader r = c.getCharacterStream();
				int temp = 0;
				while((temp=r.read()) != -1) {
					System.out.print((char)temp);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(res != null) {
				try {
					res.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
